<template>
  <div class="factor-create-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>{{ isEdit ? '编辑因子' : '创建因子' }}</h2>
        </div>
      </template>
      
      <el-form :model="form" label-width="120px" :rules="rules" ref="factorForm">
        <el-form-item label="因子名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入因子名称"></el-input>
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="基本面" value="基本面"></el-option>
            <el-option label="技术" value="技术"></el-option>
            <el-option label="估值" value="估值"></el-option>
            <el-option label="流动性" value="流动性"></el-option>
            <el-option label="市场" value="市场"></el-option>
            <el-option label="风险" value="风险"></el-option>
            <el-option label="自定义" value="自定义"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入因子描述">
          </el-input>
        </el-form-item>
        
        <el-form-item label="计算公式" prop="formula">
          <el-input
            v-model="form.formula"
            placeholder="请输入计算公式">
          </el-input>
        </el-form-item>
        
        <el-divider>高级设置</el-divider>
        
        <el-form-item label="数据源">
          <el-select v-model="form.dataSource" placeholder="选择数据源" style="width: 100%">
            <el-option label="Wind" value="wind"></el-option>
            <el-option label="CSMAR" value="csmar"></el-option>
            <el-option label="Choice" value="choice"></el-option>
            <el-option label="自定义数据" value="custom"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="计算频率">
          <el-radio-group v-model="form.frequency">
            <el-radio label="daily">日频</el-radio>
            <el-radio label="weekly">周频</el-radio>
            <el-radio label="monthly">月频</el-radio>
            <el-radio label="quarterly">季频</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="计算方法">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="公式计算" name="formula">
              <el-input
                v-model="form.formulaCode"
                type="textarea"
                :rows="6"
                placeholder="输入计算公式代码，例如：return price / earnings;">
              </el-input>
            </el-tab-pane>
            <el-tab-pane label="Python代码" name="python">
              <el-input
                v-model="form.pythonCode"
                type="textarea"
                :rows="6"
                placeholder="输入Python代码，例如：
def calculate_factor(df):
    return df['price'] / df['earnings']">
              </el-input>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">{{ isEdit ? '保存修改' : '创建因子' }}</el-button>
          <el-button @click="cancel">取消</el-button>
          <el-button v-if="!isEdit" type="success" @click="testFactor">测试因子</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 因子测试结果对话框 -->
    <el-dialog
      v-model="testDialogVisible"
      title="因子测试结果"
      width="800px">
      <div class="test-result">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="因子名称">{{ form.name }}</el-descriptions-item>
          <el-descriptions-item label="计算样本">2000个基金</el-descriptions-item>
          <el-descriptions-item label="计算时间">2.5秒</el-descriptions-item>
          <el-descriptions-item label="覆盖率">98.5%</el-descriptions-item>
        </el-descriptions>
        
        <div class="factor-stats">
          <h3>统计特性</h3>
          <el-table :data="factorStats" border style="width: 100%">
            <el-table-column prop="name" label="指标" width="180"></el-table-column>
            <el-table-column prop="value" label="数值"></el-table-column>
          </el-table>
        </div>
        
        <div class="factor-chart" style="height: 300px; margin-top: 20px;">
          <div class="chart-placeholder">
            <el-empty description="因子分析图表将在此显示"></el-empty>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="testDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm">保存因子</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'FactorCreate',
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const factorForm = ref(null)
    const activeTab = ref('formula')
    const testDialogVisible = ref(false)
    
    // 判断是否为编辑模式
    const isEdit = computed(() => {
      return route.query.mode === 'edit'
    })
    
    // 表单数据
    const form = reactive({
      id: '',
      name: '',
      category: '',
      description: '',
      formula: '',
      dataSource: 'wind',
      frequency: 'daily',
      formulaCode: '',
      pythonCode: ''
    })
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入因子名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      category: [
        { required: true, message: '请选择分类', trigger: 'change' }
      ],
      description: [
        { required: true, message: '请输入因子描述', trigger: 'blur' }
      ],
      formula: [
        { required: true, message: '请输入计算公式', trigger: 'blur' }
      ]
    }
    
    // 测试数据
    const factorStats = [
      { name: '最小值', value: '-2.341' },
      { name: '最大值', value: '5.672' },
      { name: '平均值', value: '1.124' },
      { name: '标准差', value: '0.894' },
      { name: '偏度', value: '0.231' },
      { name: '峰度', value: '3.451' },
      { name: 'IC值', value: '0.156' },
      { name: 'IR值', value: '0.823' }
    ]
    
    // 生命周期钩子
    onMounted(() => {
      // 如果是编辑模式，从store中获取因子数据
      if (isEdit.value && route.query.id) {
        const factorId = parseInt(route.query.id)
        const factor = store.getters.getFactors.find(f => f.id === factorId)
        
        if (factor) {
          Object.keys(factor).forEach(key => {
            if (form.hasOwnProperty(key)) {
              form[key] = factor[key]
            }
          })
        }
      }
    })
    
    // 测试因子
    const testFactor = () => {
      // 这里实际应该调用API来测试因子
      // 模拟测试成功
      ElMessage.success('因子测试成功')
      testDialogVisible.value = true
    }
    
    // 提交表单
    const submitForm = () => {
      factorForm.value.validate(async (valid) => {
        if (valid) {
          try {
            if (isEdit.value) {
              // 编辑已有因子
              const factorId = parseInt(route.query.id);
              await store.dispatch('updateFactor', {
                id: factorId,
                factor: { ...form }
              });
              ElMessage.success('因子更新成功');
            } else {
              // 创建新因子
              await store.dispatch('addFactor', { ...form });
              ElMessage.success('因子创建成功');
            }
            
            // 关闭测试对话框（如果打开）
            testDialogVisible.value = false;
            
            // 返回因子列表页面
            router.push('/factor-management');
          } catch (error) {
            console.error('保存因子失败:', error);
            ElMessage.error('保存失败，请稍后重试');
          }
        } else {
          ElMessage.error('请完善表单信息');
          return false;
        }
      });
    };
    
    // 取消操作
    const cancel = () => {
      router.push('/factor-management')
    }
    
    return {
      factorForm,
      form,
      rules,
      activeTab,
      testDialogVisible,
      factorStats,
      isEdit,
      testFactor,
      submitForm,
      cancel
    }
  }
}
</script>

<style scoped>
.factor-create-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.factor-stats {
  margin-top: 20px;
}

.chart-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: #f5f7fa;
}
</style> 